Object Basics
Objects are used to store keyed collections of various data and more complex entities.
In JavaScript, objects are a collection of properties, where each property is a key-value pair.
Creating an Object
let person = {
name: 'John',
age: 30,
city: 'New York'
};
Objects can be created using the object literal syntax, which is a comma-separated list of key-value pairs enclosed in curly braces.
Accessing Object Properties
console.log(person.name); // Output: John
console.log(person['age']); // Output: 30
Properties can be accessed using dot notation or bracket notation.
Adding and Modifying Properties
person.country = 'USA'; // Adds a new property
console.log(person.country); // Output: USA
person.age = 31; // Modifies an existing property
console.log(person.age); // Output: 31
Deleting Properties
delete person.city; // Deletes the 'city' property
console.log(person.city); // Output: undefined
Object Methods
Objects can also have methods, which are functions that are properties of the object.
let car = {
brand: 'Toyota',
model: 'Camry',
year: 2020,
start: function() {
console.log('Car started');
}
};
car.start(); // Output: Car started
Iterating Over Object Properties
for (let key in person) {
console.log(key + ': ' + person[key]);
}
This loop iterates over all enumerable properties of the object.
Object.keys(), Object.values(), and Object.entries()
console.log(Object.keys(person)); // Output: ['name', 'age', 'country']
console.log(Object.values(person)); // Output: ['John', 31, 'USA']
console.log(Object.entries(person)); // Output: [['name', 'John'], ['age', 31], ['country', 'USA']]
These methods return arrays of the object's keys, values, or key-value pairs, respectively.
Object Destructuring
let { name, age } = person;
console.log(name); // Output: John
console.log(age); // Output: 31
Object destructuring allows you to extract properties from an object into variables.
Nested Objects
let student = {
name: 'Alice',
age: 22,
address: {
street: '123 Main St',
city: 'Los Angeles'
}
};
console.log(student.address.city); // Output: Los Angeles
Objects can contain other objects, allowing for complex data structures.
Object Prototypes
Every object in JavaScript has a prototype, which is another object from which it inherits properties and methods. You can add properties or methods to an object's prototype using Object.prototype
.
Object.prototype.greet = function() {
console.log('Hello, ' + this.name);
};
person.greet(); // Output: Hello, John
Object Spread Operator
let newPerson = { ...person, occupation: 'Engineer' };
console.log(newPerson); // Output: { name: 'John', age: 31, country: 'USA', occupation: 'Engineer' }
The spread operator (...
) allows you to create a new object by copying properties from an existing object and adding new properties.
Object Rest Operator
let { name, ...rest } = person;
console.log(name); // Output: John
console.log(rest); // Output: { age: 31, country: 'USA' }
The rest operator (...
) allows you to extract specific properties from an object and collect the remaining properties into a new object.
Object Comparison
Objects are compared by reference, not by value. Two objects are considered equal only if they reference the same object in memory.
let obj1 = { a: 1 };
let obj2 = { a: 1 };
console.log(obj1 === obj2); // Output: false (different references)
let obj3 = obj1;
console.log(obj1 === obj3); // Output: true (same reference)
Object Freezing
You can prevent an object from being modified by using Object.freeze()
.
let frozenPerson = Object.freeze({ name: 'Bob', age: 25 });
frozenPerson.age = 30; // This will not change the age property
console.log(frozenPerson.age); // Output: 25
Object Sealing
You can prevent new properties from being added to an object and existing properties from being deleted by using Object.seal()
.
let sealedPerson = Object.seal({ name: 'Charlie', age: 28 });
sealedPerson.age = 30; // This will change the age property
console.log(sealedPerson.age); // Output: 30
sealedPerson.city = 'New York'; // This will not add a new property
console.log(sealedPerson.city); // Output: undefined
Object Cloning
You can create a shallow copy of an object using Object.assign()
or the spread operator.
let original = { a: 1, b: 2 };
let clone = Object.assign({}, original);
console.log(clone); // Output: { a: 1, b: 2 }
let spreadClone = { ...original };
console.log(spreadClone); // Output: { a: 1, b: 2 }
Note that these methods create a shallow copy, meaning nested objects are still referenced.
Object Iteration
You can iterate over the properties of an object using a for...in
loop.
for (let key in person) {
console.log(key + ': ' + person[key]);
}
This loop will log each key-value pair in the object.